<template>
  <el-drawer
    :append-to-body="true"
    :wrapperClosable="globalDisabled"
    :showClose="false"
    :with-header="false"
    size="1200px"
    :visible="open"
    @close="closeDrawer"
  >
    <div class="drawer_container">
      <div class="top_text">
        <div class="title">{{ title }}</div>
        <div class="title_box">
          <div>{{ tableList.length }}大题</div>
          <div class="line"></div>
          <div>{{ totalNum }}小题</div>
          <div class="line"></div>
          <div>{{ totalScore }}分</div>
        </div>
      </div>
      <div class="drawer_content">
        <div class="fixed_big_question" v-for="(item,index) in tableList" :key="index">
          <!--  大题操作区域     -->
          <div class="big_top">
            <div class="top_left">
              <div class="big_title">
                {{ item.title }}（{{ typeText[item.type] }}）
              </div>
            </div>
            <div class="top_right">
              <div>
                <el-input-number v-if="!globalDisabled" @change="changeTotalScore(item)" class="ipt_number_item" placeholder="请输入"
                                 v-model="item.bigTitleTotalScore" :min="0" :precision="1" :controls="false" :max="999.9" size="mini"
                />
                <span v-if="globalDisabled">{{ item.bigTitleTotalScore }}</span> 分
              </div>
              <!--   固定大题才有题目乱序选项     -->
              <el-checkbox :disabled="globalDisabled" @change="changeIsAverage(item)" v-model="item.avgFlag">
                每题平均分
                <el-tooltip placement="top">
                  <div slot="content">
                    <div v-if="item.type==1">
                      不能平均分时，优先四舍五入取一位小数，最后一题取差值 <br>
                      例：大题总分2.5分，共2小题时，第一题1.3分，第二题1.2分
                    </div>
                    <div v-if="item.type==2 || item.type==3">
                      不能平均分时，无法使用该功能
                    </div>
                  </div>
                  <i class="el-icon-question"></i>
                </el-tooltip>
              </el-checkbox>
            </div>
          </div>
          <!--   固定大题部分     -->
          <template v-if="item.type==1">
            <!--  固定大题table区域     -->
            <div class="big_table">
              <el-table
                height="100%"
                :header-cell-style="tableHeaderStyle"
                :data="item.topicList"
                class="cum_table"
              >
                <el-table-column label="序号" type="index" align="center"></el-table-column>
                <el-table-column label="题干" width="500" align="left">
                  <template slot-scope="scope">
                    <div @click="getByEditor(3,scope.row.content)" :class="{'content_html':$isIncludesHtml(scope.row.content)}"
                         class="line_feed w_fixed overTxt"
                    >{{ scope.row.content }}
                    </div>
                  </template>
                </el-table-column>
                <el-table-column label="题型" align="center" prop="topicType">
                  <template slot-scope="scope">
                    <el-tag :id="`fixed-score-${scope.row.id}`">{{ $store.getters.topicTypeText[scope.row.topicType] }}</el-tag>
                  </template>
                </el-table-column>
                <el-table-column label="难度" align="center" prop="difficulty">
                  <template slot-scope="scope">
                    <el-tag type="success">{{ $store.getters.difficultyText[scope.row.difficulty] }}</el-tag>
                  </template>
                </el-table-column>
                <el-table-column label="本题分值" align="center">
                  <template slot-scope="scope">
                    <div class="difficulty_ipt">
                      <el-input-number v-if="!globalDisabled" class="ipt_number_item" placeholder="请输入" v-model="scope.row.score"
                                       :min="0" :precision="1" :controls="false" :max="999.9" size="mini"
                      />
                      <div v-else>{{ scope.row.score }}</div>
                    </div>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </template>
          <!--   抽题大题部分    -->
          <template v-if="item.type==2">
            <!--  抽题大题table区域     -->
            <div class="big_table">
              <el-table
                height="100%"
                :header-cell-style="tableHeaderStyle"
                :data="item.containerList"
                class="cum_table"
              >
                <el-table-column label="序号" type="index" align="center"></el-table-column>
                <el-table-column label="抽题容器" width="200" align="center">
                  <template slot-scope="scope">
                    <div @click="showEditContainer(scope.row)" :id="`container-score-${scope.row.id}`" class="btn_content">
                      抽题管理（{{ scope.row.totalNum }}）
                    </div>
                  </template>
                </el-table-column>
                <el-table-column label="抽题数量" align="center" prop="extractNum"></el-table-column>
                <el-table-column label="不限难度" width="120" align="center">
                  <template slot-scope="scope">
                    <div class="difficulty_ipt">
                      <div>{{ scope.row.unlimitedNum }}</div>
                      <div class="m_5"> /</div>
                      <div>{{ scope.row.optionalUnlimitedNum }}</div>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column label="简单" width="120" align="center">
                  <template slot-scope="scope">
                    <div class="difficulty_ipt">
                      <div>{{ scope.row.easyNum }}</div>
                      <div class="m_5"> /</div>
                      <div>{{ scope.row.optionalEasyNum }}</div>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column label="中等" width="120" align="center">
                  <template slot-scope="scope">
                    <div class="difficulty_ipt">
                      <div>{{ scope.row.normalNum }}</div>
                      <div class="m_5"> /</div>
                      <div>{{ scope.row.optionalNormalNum }}</div>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column label="困难" width="120" align="center">
                  <template slot-scope="scope">
                    <div class="difficulty_ipt">
                      <div>{{ scope.row.hardNum }}</div>
                      <div class="m_5"> /</div>
                      <div>{{ scope.row.optionalHardNum }}</div>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column label="每题分值" align="center">
                  <template slot-scope="scope">
                    <div class="difficulty_ipt">
                      <el-input-number v-if="!globalDisabled" class="ipt_number_item" placeholder="请输入" v-model="scope.row.score"
                                       :min="0" :precision="1" :controls="false" :max="999.9" size="mini"
                      />
                      <div v-else>{{ scope.row.score }}</div>
                    </div>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </template>
          <!--   随机大题部分    -->
          <template v-if="item.type==3">
            <!--  随机大题table区域     -->
            <div :class="{'hide_height':item.hideTable}" class="big_table">
              <el-table
                height="100%"
                :header-cell-style="tableHeaderStyle"
                :data="item.tacticsList"
                class="cum_table"
              >
                <el-table-column label="序号" type="index"></el-table-column>
                <el-table-column label="知识点">
                  <template slot-scope="scope">
                    <div class="difficulty_ipt">
                      <el-cascader
                        size="mini"
                        :id="`tactics-score-${scope.row.id}`"
                        disabled
                        placeholder="请选择知识点"
                        v-removeAriaHidden
                        v-model="scope.row.indexId"
                        :options="courseIndexTree"
                        filterable
                        clearable
                        :props="{
                                expandTrigger: 'click',
                                checkStrictly: true,
                                emitPath: false,
                                value: 'id',
                                label: 'name',
                              }"
                      >
                      </el-cascader>
                      <div class="info_btn" @click="editTactics(scope.row)">查看</div>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column label="题型" width="120">
                  <template slot-scope="scope">
                    <div class="difficulty_ipt">
                      <el-select
                        disabled
                        size="mini"
                        filterable
                        v-model.number="scope.row.topicType"
                        placeholder="请选择题型"
                      >
                        <el-option
                          v-for="dict in dict.type.topic_type"
                          :key="Number(dict.value)"
                          :label="dict.label"
                          :value="Number(dict.value)"
                        />
                      </el-select>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column label="不限难度" width="120" align="center">
                  <template slot-scope="scope">
                    <div class="difficulty_ipt">
                      <div>{{ scope.row.unlimitedNum }}</div>
                      <div class="m_5"> /</div>
                      <div>{{ scope.row.optionalUnlimitedNum }}</div>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column label="简单" width="120" align="center">
                  <template slot-scope="scope">
                    <div class="difficulty_ipt">
                      <div>{{ scope.row.easyNum }}</div>
                      <div class="m_5"> /</div>
                      <div>{{ scope.row.optionalEasyNum }}</div>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column label="中等" width="120" align="center">
                  <template slot-scope="scope">
                    <div class="difficulty_ipt">
                      <div>{{ scope.row.normalNum }}</div>
                      <div class="m_5"> /</div>
                      <div>{{ scope.row.optionalNormalNum }}</div>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column label="困难" width="120" align="center">
                  <template slot-scope="scope">
                    <div class="difficulty_ipt">
                      <div>{{ scope.row.hardNum }}</div>
                      <div class="m_5"> /</div>
                      <div>{{ scope.row.optionalHardNum }}</div>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column label="每题分值" align="center">
                  <template slot-scope="scope">
                    <div class="difficulty_ipt">
                      <el-input-number v-if="!globalDisabled" class="ipt_number_item" placeholder="请输入" v-model="scope.row.score"
                                       :min="0" :precision="1" :controls="false" :max="999.9" size="mini"
                      />
                      <div v-else>{{ scope.row.score }}</div>
                    </div>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </template>
        </div>
      </div>
      <div class="btns" v-if="!globalDisabled">
        <el-button @click="handleClose">关闭</el-button>
        <el-button type="primary" @click="handleSubmit">保存并关闭</el-button>
      </div>
      <div class="btns" v-else>
        <el-button @click="closeDrawer(true)">关闭</el-button>
      </div>
      <!--  编辑抽题容器抽屉  -->
      <editContainerDrawer :index-id="indexId" title="抽题容器详情" :global-disabled="true" :open.sync="showContainerDrawer"
                           :container-row="currentContainerRow"
      ></editContainerDrawer>
      <!--  编辑随机策略抽屉  -->
      <editTacticsDrawer :global-disabled="true" :open.sync="showTacticsDrawer" :current-tactics-row="currentTacticsRow"
      ></editTacticsDrawer>
    </div>
    <!--  编辑弹窗  -->
    <editDrawer title="题干详情" :show.sync="showDrawer" :openType="propOpenType" :propEditorValue="propEditorValue"></editDrawer>
  </el-drawer>
</template>

<script>
import editContainerDrawer from './editContainerDrawer'
import editTacticsDrawer from './editTacticsDrawer'
import editDrawer from '@/views/tea_course/components/editDrawer'
import { updateBatchScoreApi } from '@/api/ExaminationModule'

export default {
  name: 'settingScoreDrawer',
  dicts: ['topic_type'],
  components: {
    editDrawer,
    editTacticsDrawer,
    editContainerDrawer
  },
  props: {
    open: {
      type: Boolean,
      default: false
    },
    titleList: {
      type: [Object, Array],
      default: () => {
        return []
      }
    },
    courseIndexTree: {
      type: [Object, Array],
      default: () => {
        return []
      }
    },
    paperId: {
      type: [String, Number],
      default: ''
    },
    indexId: {
      type: [String, Number],
      default: ''
    },
    globalDisabled: {
      type: [Boolean],
      default: false
    },
    title: {
      type: String,
      default: '考核配分'
    }
  },
  data() {
    return {
      totalNum: 0,
      totalScore: 0,
      //编辑随机策略布尔值
      showTacticsDrawer: false,
      //当前随机策略整行数据
      currentTacticsRow: {},
      showContainerDrawer: false,
      currentContainerRow: {},
      typeText: {
        1: '固定大题',
        2: '抽题大题',
        3: '随机大题'
      },
      //富文本录入类型 1：添加 2：编辑 3：查看
      propOpenType: 1,
      //富文本录入抽屉状态
      showDrawer: false,
      //富文本录入组件---内容
      propEditorValue: '',
      tableList: [],
      //表头样式
      tableHeaderStyle: {
        'background-color': '#f8f8f9',
        'color': '#333333',
        'font-size': '14px',
        'font-family': 'PingFangSC, PingFang SC',
        'font-weight': '400'
      }
    }
  },
  watch: {
    open(val) {
      if (val) {
        let tableList = JSON.parse(JSON.stringify(this.titleList))
        tableList.forEach((item) => {
          item.bigTitleTotalScore = item.score ? item.score : undefined
          item.avgFlag = false
        })
        this.tableList = tableList
      }
    },
    tableList: {
      handler(val) {
        let totalNum = 0
        let totalScore = 0
        val.forEach(item => {
          if (item.type == 1) {
            item.topicList.forEach((topicItem) => {
              totalNum++
              totalScore += topicItem.score
            })
          }
          if (item.type == 2) {
            item.containerList.forEach((topicItem) => {
              if (topicItem.extractNum > 0) {
                for (let i = 0; i < topicItem.extractNum; i++) {
                  totalNum++
                  totalScore += topicItem.score
                }
              }
            })
          }
          if (item.type == 3) {
            item.tacticsList.forEach((topicItem) => {
              if (topicItem.extractNum > 0) {
                for (let i = 0; i < topicItem.extractNum; i++) {
                  totalNum++
                  totalScore += topicItem.score
                }
              }
            })
          }
        })
        this.totalNum = totalNum
        this.totalScore = totalScore.toFixed(1)
      },
      deep: true
    }
  },
  methods: {
    //富文本录入
    getByEditor(type, Value) {
      if (type == 3 && !this.$isIncludesHtml(Value)) {
        return
      }
      this.propEditorValue = Value
      this.propOpenType = type
      this.showDrawer = true
    },
    //编辑随机策略
    editTactics(row) {
      this.currentTacticsRow = row
      this.showTacticsDrawer = true
    },
    //添加抽题容器
    showEditContainer(row) {
      this.currentContainerRow = row
      this.showContainerDrawer = true
    },
    changeTotalScore(item) {
      if (item.avgFlag) {
        this.averageEveryScore(item)
      }
    },
    changeIsAverage(item) {
      if (item.avgFlag) {
        this.averageEveryScore(item)
      }
    },
    averageEveryScore(item) {
      this.tableList.forEach((value) => {
        if (value.id == item.id) {
          if (value.type == 1) {
            value.topicList = this.distributeScores(value.topicList, item.bigTitleTotalScore, 'score', value.topicList.length)
          }
          if (value.type == 2) {
            //保留一位小数除不尽
            console.log(value, 'valuevaluevalue')
            let bol = this.isExactlyDivisible(item.bigTitleTotalScore, value.topicNum)
            if (bol) {
              value.containerList = this.distributeScores(value.containerList, item.bigTitleTotalScore, 'score', value.topicNum)
            } else {
              this.$modal.msgWarning('平均分失败，分数无法平均分配到每小题（小数点后一位），请重新输入')
              value.containerList.forEach((item) => {
                item.score = undefined
              })
            }
          }
          if (value.type == 3) {
            let bol = this.isExactlyDivisible(item.bigTitleTotalScore, value.topicNum)
            if (bol) {
              value.tacticsList = this.distributeScores(value.tacticsList, item.bigTitleTotalScore, 'score', value.topicNum)
            } else {
              this.$modal.msgWarning('平均分失败，分数无法平均分配到每小题（小数点后一位），请重新输入')
              value.tacticsList.forEach((item) => {
                item.score = undefined
              })
            }
          }
        }
      })
    },
    //判断保留1位小数的情况下，两个数相除是否能除尽
    isExactlyDivisible(dividend, divisor) {
      console.log(dividend, dividend)
      const rawValue = dividend / divisor
      const roundedValue = parseFloat(rawValue.toFixed(1)) // 保留1位小数
      // 比较原始值和保留1位后的值是否相同（考虑浮点数精度问题）
      return Math.abs(rawValue - roundedValue) < 1e-9
    },
    //平均配分方法
    distributeScores(examScoreList, totalScore, key, totalNum) {
      const processTotalNum = totalNum
      const averageScore = (totalScore / processTotalNum).toFixed(1) // 计算平均分数并保留两位小数
      let remainingScore = (totalScore - averageScore * (processTotalNum - 1)).toFixed(1) // 计算剩余的分数并保留两位小数
      examScoreList.forEach((item, index) => {
        if (index === processTotalNum - 1) {
          // 最后一个元素
          item[key] = parseFloat(remainingScore) // 将剩余分数转换为浮点数
        } else {
          item[key] = parseFloat(averageScore) // 将平均分数转换为浮点数
        }
      })
      return examScoreList
    },
    closeDrawer(bol) {
      if (this.globalDisabled || bol) {
        this.$emit('update:open', false)
      }
    },
    //关闭抽屉
    handleClose() {
      this.$confirm('试卷配分未保存，关闭后将失去本次操作数据，是否确认关闭弹窗？', '关闭确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        this.$emit('update:open', false)
      }).catch(() => {
        this.$modal.msgInfo('已取消')
      })
    },
    async handleSubmit() {
      let text = ''
      let errorData = this.checkErrorStatus()
      if (errorData.hasZeroScore) {
        text = `<div style="color: #e95756;">仍有题目未配分;<br>${errorData.text}总分与小题分数总和不一致，总分将自动变更为小题分数总和。<br><span style="color: #999999;">是否确认保存？</span></div>`
      } else {
        text = `<div style="color: #e95756;">${errorData.text}总分与小题分数总和不一致，总分将自动变更为小题分数总和。<br><span style="color: #999999;">是否确认保存？</span></div>`
      }
      if (!errorData.text) {
        text = '是否确认保存配分?'
      }
      this.$confirm(text, '保存确认', {
        dangerouslyUseHTMLString: true,
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        let params = []
        for (const argument of this.tableList) {
          let obj = {
            titleId: argument.id,
            titleScore: 0,
            type: argument.type,
            avgFlag: argument.avgFlag,
            topics: []
          }
          if (argument.type == 1) {
            argument.topicList.forEach(item => {
              obj.topics.push({
                id: item.paperTopicId,
                topicScore: item.score ? item.score : null
              })
              obj.titleScore += item.score ? item.score : 0
            })
          }
          if (argument.type == 2) {
            argument.containerList.forEach(item => {
              obj.topics.push({
                id: item.id,
                topicScore: item.score ? item.score : null
              })
              obj.titleScore += item.score ? item.score * item.extractNum : 0
            })
          }
          if (argument.type == 3) {
            argument.tacticsList.forEach(item => {
              obj.topics.push({
                id: item.id,
                topicScore: item.score ? item.score : null
              })
              obj.titleScore += item.score ? item.score * item.extractNum : 0
            })
          }
          params.push(obj)
        }
        const loading = this.$loading({
          lock: true,
          text: '正在保存...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.3)'
        })
        try {
          let res = await updateBatchScoreApi(this.paperId, params)
          const { code } = res
          if (code == 200) {
            this.$modal.msgSuccess('保存成功')
            this.$emit('update:open', false)
            this.$emit('refresh')
          }
        } catch (e) {
          console.error(e)
        } finally {
          loading.close()
        }
      }).catch(() => {
        this.$modal.msgInfo('已取消')
      })
    },
    //锚点跳转
    scrollToAnchor(id) {
      const anchor = document.getElementById(id)
      console.log(anchor)
      if (anchor) {
        anchor.scrollIntoView({ behavior: 'smooth' })
      }
    },
    checkErrorStatus() {
      let text = ''
      let hasZeroScore = false
      this.tableList.forEach((item) => {
        if (item.type == 1) {
          let score = 0
          item.topicList.forEach((topicItem) => {
            if (!topicItem.score) {
              hasZeroScore = true
            }
            score += topicItem.score ? topicItem.score : 0
          })
          if ((score.toFixed(1) - 0) != item.bigTitleTotalScore) {
            text += `【${item.title}】`
          }
        }
        if (item.type == 2) {
          let score = 0
          item.containerList.forEach((topicItem) => {
            if (!topicItem.score) {
              hasZeroScore = true
            }
            score += topicItem.score ? topicItem.score * topicItem.extractNum : 0
          })
          if ((score.toFixed(1) - 0) != item.bigTitleTotalScore) {
            text += `【${item.title}】`
          }
        }
        if (item.type == 3) {
          let score = 0
          item.tacticsList.forEach((topicItem) => {
            if (!topicItem.score) {
              hasZeroScore = true
            }
            score += topicItem.score ? topicItem.score * topicItem.extractNum : 0
          })
          if ((score.toFixed(1) - 0) != item.bigTitleTotalScore) {
            text += `【${item.title}】`
          }
        }
      })
      return { text, hasZeroScore }
    }
  }
}
</script>

<style scoped lang="scss">
@import "../../../assets/styles/mixin.scss";

.drawer_container {
  width: 100%;

  .top_text {
    padding: 24px;
    box-sizing: border-box;
    display: flex;
    align-items: center;
    justify-content: space-between;

    .title {
      font-family: PingFangSC, PingFang SC, sans-serif;
      font-weight: 500;
      font-size: 16px;
      color: #333333;
    }

    .title_box {
      display: flex;
      align-items: center;
      gap: 0 10px;
      color: #999999;
      font-family: PingFangSC, PingFang SC, sans-serif;
      font-weight: 400;
      font-size: 14px;

      .line {
        width: 1px;
        height: 16px;
        background: #E8EAEB;
      }
    }
  }

  .drawer_content {
    border-top: 1px solid #E8EAEB;
    width: 100%;
    height: calc(100vh - 154px);
    overflow: auto;
    padding: 0 24px;
    box-sizing: border-box;

    .fixed_big_question {
      width: 100%;

      .big_top {
        margin-top: 16px;
        width: 100%;
        display: flex;
        align-items: center;
        justify-content: space-between;

        .top_left {
          display: flex;
          align-items: center;
          gap: 0 12px;

          .big_title {
            font-family: PingFangSC, PingFang SC, sans-serif;
            font-weight: 500;
            font-size: 14px;
            color: #333333;
          }
        }

        .top_right {
          display: flex;
          gap: 0 16px;
          align-items: center;
        }
      }

      .big_table {
        margin-top: 16px;
        width: 100%;
        height: 344px;
        overflow: hidden;
        transition: all 0.3s ease-in-out;

        .cum_table {
          width: 100%;
          border-radius: 8px;
          border: 1px solid #E8EAEB;

          .btn_content {
            @include btn_plain(rgba(0, 0, 0, 0.06), #28B28B) {
              width: 120px;
              height: 32px;
              border-radius: 4px;
            }
          }

          .difficulty_ipt {
            width: 100%;
            display: flex;
            justify-content: center;
            align-items: center;

            .el-icon-edit {
              margin-left: 6px;
              font-size: 16px;
            }
          }

          .icon_box {
            width: 100%;
            display: flex;
            justify-content: center;
            align-items: center;
            gap: 0 8px;
          }
        }

        ::v-deep .el-table:before {
          height: 0;
        }
      }
    }
  }

  .btns {
    margin-top: 20px;
    width: 100%;
    padding: 0 24px;
    box-sizing: border-box;
    display: flex;
    justify-content: flex-end;
  }
}

.info_btn {
  color: #28B28B;
  cursor: pointer;
  margin-left: 6px;
  user-select: none;
}

.ipt_number_item {
  width: 70px !important;
}

.content_html {
  position: relative;
  cursor: pointer;
  height: 100%;

  &:hover {
    user-select: none;

    &:after {
      content: '预览';
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      display: flex;
      align-items: center;
      justify-content: center;
      border-radius: 4px;
      color: #ffffff;
      background: rgba(0, 0, 0, .2);
    }
  }
}

.w_fixed {
  width: 100%;
}
</style>
